import axios from 'axios'

import { Toast } from 'vant'

// 引入md5的包
import CryptoJS from 'crypto-js'
// import JsBridge from "./../utils/JsBridge.js"

// 使用bridge需要实例vue对象
import Vue, { h } from 'vue'
const app = new Vue()
import JsBridge from './../utils/JsBridge.js'

console.log(JsBridge, 'JsBridge')

// 按需处理header start
// 项目没有userAgent标识，所以用环境变量来判断 process.env.ENV
// import {browser} from '@/utils/browser'
// console.log(browser.versions.android,'browser.versions.android')

let nonceDom = generateRandomString(16)
// 生成随机数
function generateRandomString(length) {
  const characters =
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let randomString = ''

  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length)
    randomString += characters.charAt(randomIndex)
  }

  return randomString
}

// 新弄请求头 start
const signHeaders = [
  'Authorization',
  'X-Sdk-Version',
  'X-App-Id',
  'X-Client',
  'X-Nonce',
  'X-Dc',
  'X-User-Id'
]
let signSecret = {}
let infoObj = {}
let md5Str = ''

// 处理加密参数
// dataObj 传入的参数 主要是赋值给md5加密的字符串
function handleData(dataObj) {
  let filteredObject = ''
  // 处理相关参数
  let headerObj = {
    Authorization: signSecret.token,
    'X-Client': signSecret.sdkDeviceId,
    'X-App-Id': signSecret.sdkAppId,
    'X-Sdk-Version': signSecret.sdkVersion,
    'X-Nonce': signSecret.nonce,
    'X-User-Id': infoObj.userId,
    'X-Dc': signSecret.dc,
  }
  console.log(headerObj, 'headerObj')
  if (dataObj) {
    filteredObject = Object.fromEntries(
      Object.entries(dataObj).filter(
        ([_, value]) => value !== null && value !== '' && value !== undefined,
      ),
    )
  }

  const sortedHeaders = Object.entries(headerObj)
    .filter(([key]) => signHeaders.includes(key))
    .sort(([aKey], [bKey]) => aKey.localeCompare(bKey))
    .map(([, value]) => value)
  console.log(sortedHeaders, 'sortedHeaders')
  // 将URL参数按键的字典序排序
  const sortedParams = Object.entries(filteredObject)
    .sort(([aKey], [bKey]) => aKey.localeCompare(bKey))
    .map(([key, value]) => value)
  const rawStr = [...sortedHeaders, ...sortedParams, signSecret.secret].join(
    '&',
  )
  console.log(rawStr, 'rawStr')
  md5Str = CryptoJS.MD5(rawStr).toString()
}
// 新弄请求头 end

Object.assign(axios.defaults, {
  timeout: 20 * 1000,
  baseURL: process.env.BASE_API,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  },
})

export default function createAxios(conf = {}, type = 'login') {
  const service = axios.create(conf)
  // request拦截器
  service.interceptors.request.use(config => {
    // 运行赋值函数
    return new Promise((resolve, reject) => {
      if (process.env.ENV == 'dev') {
        // 测试线写固定参数
        signSecret = {
          secret:
            'bNV6SIB8S31mQXay&V9#HmhbJoQK1FxnIIk6SjlfCpJxNv7UE6!0NL6uqN5r9GRL', ///密钥
          token:
            'eJyrVgrxCdYrSy1SslIy0jNQ0gHzM1NS80oy0zLBwoaGRkBkZAGVK07JTiwoyExRsjI0MDAwhAimVhRkFqUChcwNzCxNDCxNzSDiJZm5UFFjYzNDmGhxZjrQXJ-cwlCvCB-zEGd3w8LKZMdiL8Oi9Ows12Rno6Icn2RLj2zT4syqlHBjt2JbpVoAnKwwpQ__', ///凭证：Authorization
          sdkAppId: 10001, ///appID
          sdkVersion: '2.8.0', ///app版本
          sdkDeviceId: 'iOS@@iPhone@@15.1@@0', ///设备id
          nonce: nonceDom, ///16位加密随机数
          dc: 'SMeF+zhuZpbhizn+ZDyjNYapkASPr9krbOYS/fUx/5XTmfI7G5Zg24QWt1htfcPuf01G4mEchQ4HBgAvkcINiGwhWh0P2osprIY+gozboX8=', ///设备的id号码（X-Dc）
          isTest: 1, ///1 测试环境 0 非测试环境
          // userId: '315608',
          userId: '1001929',
        }
        infoObj.userId = '1001929';
        if (config.data) {
          handleData(config.data)
        } else {
          handleData(config.params)
        }

        if (signSecret) {
          console.log(signSecret,'设置signSecret')
          // 添加header
          config.headers['Authorization'] = signSecret.token
            config.headers['X-App-Id'] = signSecret.sdkAppId
            config.headers['X-Client'] = signSecret.sdkDeviceId
            config.headers['X-Nonce'] = signSecret.nonce
            config.headers['X-Dc'] = signSecret.dc
            config.headers['X-Sdk-Version'] = signSecret.sdkVersion
            config.headers['X-User-Id'] = infoObj.userId
            config.headers['X-Sign'] = md5Str
          // config.headers['X-Debug'] = 1
          // 增加header列表
        }

        //  console.log(config,'config')

        resolve(config)

        // infoObj.userId = ;
      } else {
        console.log("现在是开发线啦;;;1111111111111");
        JsBridge.callHandler('current_token', {}, data => {
          signSecret = JSON.parse(data)
          console.log(signSecret,'获取signSecret')
          JsBridge.callHandler('current_user', {}, data => {
            infoObj = JSON.parse(data);
            console.log(infoObj,'获取infoObj')
          // console.log("获取getAppData的数据",JSON.parse(data))
          // console.log("有回调吗", data);
          // signSecret = JSON.parse(data);
          
          if (config.data) {
            handleData(config.data)
          } else {
            handleData(config.params)
          }

          // console.log(signSecret,'获取signSecret')

          if (signSecret) {
            // console.log(signSecret,'设置signSecret')
            // 添加header
            config.headers['Authorization'] = signSecret.token
            config.headers['X-App-Id'] = signSecret.sdkAppId
            config.headers['X-Client'] = signSecret.sdkDeviceId
            config.headers['X-Nonce'] = signSecret.nonce
            config.headers['X-Dc'] = signSecret.dc
            config.headers['X-Sdk-Version'] = signSecret.sdkVersion
            config.headers['X-User-Id'] = infoObj.userId
            config.headers['X-Sign'] = md5Str
            // 增加header列表
          }
           console.log(config,'到这块返回')
          resolve(config)
          //  console.log(config,'到这块返回-1')
        })
      })
      }
    })
  })
  service.interceptors.response.use(
    response => {
      const res = response.data
      // console.log(res,'lll')
      // if the custom code is not 20000, it is judged as an error.
      if (res.errorCode == 0 || res.code === 200) {
        return res
      } else {
        // Toast.fail({
        //   message: res.errorMsg || res.message,
        //   className: 'errorToast',
        // })
        return res
        // return Promise.reject(res)
      }
    },
    error => {
      Toast.fail({
        message: '网络错误,请退出重新尝试',
        className: 'errorToast',
      })
      return Promise.reject(error)
    },
  )
  return service
}
